package com.cheer.controller;

import com.cheer.dto.PasswordUpdateDTO;
import com.cheer.service.UserService;
import com.cheer.vo.Result;
import com.cheer.vo.Page;
import com.cheer.dto.*;
import com.cheer.vo.UserListVO;
import com.cheer.vo.UserVO;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.collections4.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.validation.Valid;
import java.util.List;

/**
 * @author cheer
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;

    @ApiOperation("获取当前登录信息")
    @GetMapping("/info")
    public Result<UserVO> getUserInfo() {
        return Result.success(userService.getCurrentUser());
    }

    @ApiOperation("修改密码")
    @PostMapping("/password/update")
    public Result updatePassword(@RequestBody @Valid PasswordUpdateDTO param) {
        userService.updatePassword(param.getOldPassword(), param.getNewPassword());
        return Result.success();
    }

    @ApiOperation("查询用户分页列表")
    @PostMapping("/list")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result<Page<UserListVO>> list(@RequestBody UserQueryDTO userQueryDTO) {
        return Result.success(userService.listByPage(userQueryDTO));
    }

    @ApiOperation("密码重置")
    @GetMapping("/reset")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result reset(@RequestParam Long id) {
        userService.reset(id);
        return Result.success();
    }

    @ApiOperation("批量删除")
    @PostMapping("/delete")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result delete(@RequestBody List<Long> ids) {
        if (CollectionUtils.isNotEmpty(ids)) {
            userService.removeByIds(ids);
        }
        return Result.success();
    }

    @ApiOperation("启用或禁用")
    @PostMapping("/locked")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result updateLocked(@RequestBody @Valid UserLockedDTO param) {
        userService.updateLocked(param);
        return Result.success();
    }

    @ApiOperation("修改用户")
    @PostMapping("/update")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result update(@RequestBody @Valid UserUpdateDTO userUpdateDTO) {
        userService.update(userUpdateDTO);
        return Result.success();
    }

    @ApiOperation("添加用户")
    @PostMapping("/add")
    @PreAuthorize("@permissionValidator.isAdmin()")
    public Result add(@RequestBody @Valid UserAddDTO userAddDTO) {
        userService.add(userAddDTO);
        return Result.success();
    }
}
